package com.bobo.encryption.symmetric;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

/**
 * Java实现对称加密（3重DES）
 * 
 * 加密级别 DES<3DES<AES<PBE
 * @author win7
 *
 */
public class DES3test {

	public static String bobo="www.bobo.com";
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Jdk3DES();
	}

	public static void Jdk3DES(){
		try {
		//1.初始化key秘钥	
			KeyGenerator keyGenerator=KeyGenerator.getInstance("DESede");
			keyGenerator.init(new SecureRandom());
			SecretKey secretkey= keyGenerator.generateKey();
			//转换key秘钥
			DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(secretkey.getEncoded());
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
			Key  key = secretKeyFactory.generateSecret(deSedeKeySpec);
			
		//2.加密
			Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] result= cipher.doFinal(bobo.getBytes());
			System.out.println("jdk 3des 加密："+HexBin.encode(result));//转成10进制编码
		
		//解密
			cipher.init(Cipher.DECRYPT_MODE, key);
			result= cipher.doFinal(result);
			System.out.println("jdk 3des 解密："+new String(result));//byte[]转成Sting字符串
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
